<?php

namespace Biz\service\SuperSubsidy;

use Biz\model\SuperSubsidy\YouZanBrandItemModel;
use Biz\model\SuperSubsidy\YouZanBrandUserModel;
use Biz\model\SuperSubsidy\YouZanFullOrderInfo;
use Biz\model\SuperSubsidy\YouZanOrderInfo;
use Biz\model\SuperSubsidy\YouZanOrders;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\model\Phone as PhoneModel;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\tools\Log;
use Doraemon\tools\Youzan;
use hhz\constant\basic\UserExtendPhoneScene;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;

class YouZanOrder implements ConstInterface
{
    use _Async;

    private static $createDataDebug = false;

    /**
     * 搜索品牌的订单
     * @param $brandUserId
     * @param $page
     * @param $pageSize
     * @param array $params
     * @return array|void
     */
    public static function searchBrandOrder($brandUserId, $page = 1, $pageSize = 20, array $params = [])
    {
        $data = [];
        $where = [
            'brand_user_id' => $brandUserId,
            'LIMIT' => [($page - 1) * $pageSize, $pageSize]
        ];
        if (is_null($brandUserId)) {
            unset($where['brand_user_id']);
        }
        $where = array_merge($where, $params);
        $brandInfo = YouZanBrandUserModel::getByWhere(['id' => $brandUserId]);
        $ordersList = YouZanOrders::selectByWhere($where);
        if (empty($brandInfo)) {
            $brandUserIds = $ordersList ? array_column($ordersList, 'brand_user_id') : [];
            $brandInfos = $brandUserIds ? YouZanBrandUserModel::selectByWhere(['id' => $brandUserIds]) : [];
            $brandInfos = $brandInfos ? array_column($brandInfos, null, 'id') : [];
        } else {
            $brandInfos[$brandInfo['id']] = $brandInfo;
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $count = YouZanOrders::selectCountWhere($where);
        if ($ordersList) {
            $tids = array_column($ordersList, 'tid');
            $itemIds = $ordersList ? array_column($ordersList, 'item_id') : [];
            $itemIds = array_filter(array_unique($itemIds));

            $ordersList = array_column($ordersList, null, 'oid');

            $tids = array_unique($tids);
            $orderInfoList = YouZanOrderInfo::selectByWhere(['tid' => $tids]);
            $orderInfoList = array_column($orderInfoList, null, 'tid');
            $receiverTelEncryptIds = array_column($orderInfoList, 'receiver_tel_encrypt_id');
            $getReceliverTelPhones = self::batchGetDecryptPhones($receiverTelEncryptIds);

            $brandItemInfos = $itemIds ? YouZanBrandItemModel::selectByWhere(['item_id' => $itemIds]) : [];
            $brandItemPriceArr = [];
            foreach ($brandItemInfos as $row) {
                $brandItemPriceArr[$row['item_id']][$row['sku_id']] = [
                    'supply_price' => $row['supply_price'],
                    'market_price' => $row['market_price'],
                    'hhz_price' => $row['hhz_price'],
                    'commission' => $row['commission']
                ];
            }

            foreach ($ordersList as $oid => $orderDetail) {
                $tid = $orderDetail['tid'];
                $orderInfo = $orderInfoList[$tid] ?? [];
                if ($orderInfo) {
                    $skuValues = [];
                    $skuProArr = $orderDetail['sku_properties_name'] ? json_decode($orderDetail['sku_properties_name'], true) : [];
                    foreach ($skuProArr as $skuItem) {
                        $skuValues[] = $skuItem['v'];
                    }
                    $itemId = $orderDetail['item_id'];
                    $skuId = $orderDetail['sku_id'] ?? 0;
                    $supplyPrice = 0;
                    $commission = 0;
                    if (isset($brandItemPriceArr[$itemId][$skuId])) {
                        $supplyPrice = $brandItemPriceArr[$itemId][$skuId]['supply_price'];
                        $commission = $brandItemPriceArr[$itemId][$skuId]['commission'];
                    } else if (isset($brandItemPriceArr[$itemId][0])) {
                        $supplyPrice = $brandItemPriceArr[$itemId][0]['supply_price'];
                        $commission = $brandItemPriceArr[$itemId][0]['commission'];
                    }
                    $totalSupplyPrice = bcmul($orderDetail['num'], $supplyPrice, 2);
                    $commission = bcmul($orderDetail['num'], $commission, 2);
                    $receiverTel = ($orderInfo['receiver_tel_encrypt_id'] &&
                        isset($getReceliverTelPhones[$orderInfo['receiver_tel_encrypt_id']])
                        && $getReceliverTelPhones[$orderInfo['receiver_tel_encrypt_id']])
                        ? $getReceliverTelPhones[$orderInfo['receiver_tel_encrypt_id']] : $orderInfo['receiver_tel'];
                    $data[] = [
                        'tid' => $tid,//订单编号
                        'oid' => (string)$oid,//订单明细id
                        'brand' => $brandInfos[$orderDetail['brand_user_id']]['brand_name'] ?? '',//带货品牌
                        'title' => $orderDetail['title'],//商品名称
                        'item_id' => $orderDetail['item_id'],//商品ID
                        'alias' => $orderDetail['alias'],//商品别称
                        'item_barcode' => $orderDetail['item_barcode'],//商品条码
                        'sku_id' => $orderDetail['sku_id'],//规格id
                        'sku_barcode' => $orderDetail['sku_barcode'],//规格条码,
                        'is_deliver_goods' => $orderDetail['is_deliver_goods'],//商品发货状态 是否已发货  未发货、已发货
                        'refund_state' => $orderDetail['refund_state'],//商品退款状态
                        'refund_time' => strtotime($orderDetail['refund_time']) > 0 ? $orderDetail['refund_time'] : '',//商品退款时间
                        'dist_id' => $orderDetail['dist_id'],//包裹id
                        'express_id' => $orderDetail['express_id'],//商品发货物流公司
                        'express_name' => $orderDetail['express_name'],//商品发货物流公司
                        'express_no' => $orderDetail['express_no'],//商品发货物流单号
                        'created' => $orderInfo['created'],//订单创建时间
                        'created_time' => $orderInfo['created'],//订单创建时间
                        'pay_time' => $orderInfo['pay_time'],//买家付款时间
                        'sku_properties_name' => implode(' ', $skuValues),//商品规格
                        'num' => $orderDetail['num'],//商品数量
                        'payment' => $orderDetail['payment'],//商品最终均摊价 单位:元
                        'commission' => $commission,//订单佣金 好好住配置*商品数量  订单结算价
                        'supply_price' => $supplyPrice > 0 ? $supplyPrice : '',//供货价 好好住配置
                        'total_supply_price' => $totalSupplyPrice > 0 ? $totalSupplyPrice : '',// 供货价小记 好好住配置计算
                        'receiver_name' => $orderInfo['receiver_name'],//收货人姓名
                        'receiver_tel' => $receiverTel,//收货人手机号
                        'delivery_province' => $orderInfo['delivery_province'],//收货地址 省
                        'delivery_city' => $orderInfo['delivery_city'],//收货地址 市
                        'delivery_district' => $orderInfo['delivery_district'],//收货地址 区
                        'delivery_address' => $orderInfo['delivery_address'],//收货地址 详细地址
                        'buyer_message' => $orderInfo['buyer_message'],//买家留言
                        'trade_memo' => $orderInfo['trade_memo'],//卖家留言
                    ];
                }
            }
        }
        return [$data, $count];
    }

    public static function searchCreateOrder($startUpdate, $endUpdate, $tid = '', $debug = false)
    {
        $searchAlltids = [];
        $allCount = 0;
        self::$createDataDebug = $debug;
        //订单批量接口：https://doc.youzanyun.com/detail/API/0/2971  youzan.trades.sold.get.4.0.2
        //订单详情接口 https://doc.youzanyun.com/detail/API/0/3757   youzan.trade.get.4.0.2
        if (is_null($startUpdate) || is_null($endUpdate)) {
            $endUpdate = date('Y-m-d H:i:s');
            $startUpdate = date('Y-m-d H:i:s', strtotime('-1 days', strtotime($endUpdate)));
        }
        $params = [
            'start_update' => $startUpdate,
            'end_update' => $endUpdate,
            'need_order_url' => true,
        ];
        if (!empty($tid)) {
            $params = [
                'keywords' => $tid,
                'need_order_url' => true,
            ];
        }
        self::logCreateOrderData('同步订单params', $params);
        $page = 1;
        $pageSize = 100;
        do {
            $orderList = Youzan::searchOrderList($page, $pageSize, $params);
            $total = $orderList['total_results'] ?? 0;
            $fullOrderInfoList = $orderList['full_order_info_list'] ?? [];
            self::logCreateOrderData('查询订单总数：' . $total . '#page:' . $page . '#订单数:' . count($fullOrderInfoList));
            if ($fullOrderInfoList) {
                foreach ($fullOrderInfoList as $row) {
                    if (YouZanOrderInfo::STATUS_WAIT_BUYER_PAY == $row['full_order_info']['order_info']['status']
                        || $row['full_order_info']['order_info']['pay_type'] == 0
                        || strtotime($row['full_order_info']['order_info']['pay_time']) <= 0
                    ) {//未付款的订单不记录
                    } else {
                        $tids = self::createOrderData($row);
                        $searchAlltids = array_merge($searchAlltids, $tids);
                    }
                }
                $allCount += $total;
            }
            $page++;
        } while ($fullOrderInfoList);
        self::logCreateOrderData('更新' . $allCount . '条订单', []);
        return [$allCount, $searchAlltids];
    }

    public static function searchRefundOrders(int $startUpdate, int $endUpdate, $debug = false, array $filterTids = [])
    {
        if (is_null($startUpdate) || is_null($endUpdate)) {
            $startUpdate = strtotime('-2 hours');
            $endUpdate = time();
        }
        $params = [
            'update_time_start' => $startUpdate,
            'update_time_end' => $endUpdate,
        ];
        $res = Youzan::refundSearch(1, 100, $params);
        $tids = [];
        if ($res && $res['refunds']) {
            foreach ($res['refunds'] as $row) {
                $tids[] = $row['tid'];
            }
        }
        $tids = array_unique($tids);
        if ($filterTids) {
            $tids = array_diff($tids, $filterTids);
        }
        foreach ($tids as $tid) {
            self::searchCreateOrder(null, null, $tid, $debug);
        }
        $count = count($tids);
        return [$count, $tids];
    }

    private static function createOrderData($soldOrder)
    {
        $tids = [];
        $allExpress = json_decode(self::YOU_ZAN_EXPRESS, true);
        $soldOrderJson = json_encode($soldOrder);
        $orderInfoDataArr = [];//订单基础信息
        $ordersDataArr = [];//订单商品交易明细
        foreach ($soldOrder as $row) {
            $tid = $row['order_info']['tid'];//订单号
            $tids[] = $tid;
            self::logCreateOrderData('同步订单：' . $tid);
            $orderInfoDataArr[$tid] = [
                //订单基础信息 start
                'tid' => $row['order_info']['tid'],//订单号
                'type' => $row['order_info']['type'],//主订单类型0:普通订单; 1:送礼订单; 2:代付; 3:供货商查询时返回表示为分销供货单。; 4:赠品; 5:心愿单; 6:二维码订单; 7:合并付货款; 8:1分钱实名认证; 9:品鉴; 10:拼团; 15:返利; 35:酒店; 40:外卖; 41:堂食点餐; 46:外卖买单; 51:全员开店; 61:线下收银台订单; 71:美业预约单; 72:美业服务单; 75:知识付费; 81:礼品卡;85：直播带货订单（仅指爱逛平台产生的订单） 100:批发;89:样品订单
                'status' => $row['order_info']['status'],//主订单状态 WAIT_BUYER_PAY （等待买家付款，定金预售描述：定金待付、等待尾款支付开始、尾款待付）； TRADE_PAID（订单已支付 ）； WAIT_CONFIRM（待确认，包含待成团、待接单等等。即：买家已付款，等待成团或等待接单）； WAIT_SELLER_SEND_GOODS（等待卖家发货，即：买家已付款）； WAIT_BUYER_CONFIRM_GOODS (等待买家确认收货，即：卖家已发货) ； TRADE_SUCCESS（买家已签收以及订单成功）； TRADE_CLOSED（交易关闭）； PS：TRADE_PAID状态仅代表当前订单已支付成功，表示瞬时状态，稍后会自动修改成后面的状态。如果不关心此状态请再次请求详情接口获取下一个状态。
                'status_str' => $row['order_info']['status_str'],//主订单状态 描述
                'pay_type' => $row['order_info']['pay_type'],//支付类型；WEIXIN-微信支付(1); WEIXIN_DAIXIAO-微信代销支付类型，包含如下支付渠道：[WXPAY_DAIXIAO-微信支付(10);WXPAY_SHOULI-受理模式(11);WX_APPPAY-sdk支付(13);WX_WAPPAY-微信支付(19);WX_HB-微信红包支付(20);BARCODE_WX-微信支付(29);WX_NATIVE-微信支付(72);OF_YOUZAN_QR-收款码(101);OF_WEIXIN-微信(102)]； ALIPAY-支付宝支付类型，包含如下支付渠道：[ALIWAP-支付宝-用户付(2);ALIPAY-支付宝-用户付(3);BARCODE_ALIPAY-支付宝-商家扫(30);ALIPAY_HBFQ-支付宝花呗分期支付(53);OF_ALIPAY-支付宝支付(103);MARK_PAY_ALIPAY-标记支付-支付宝(111);ALIPAY_FLOWER-花呗支付(4095); ALIPAY_AGREEMENT-支付宝免密支付(4096); ALIPAY_APPLET-支付宝-用户付(4097)]； BANKCARDPAY-银行卡支付类型，包含如下支付渠道：[ UNIONPAY-(4);UNIONWAP-(6);UMPAY-联动优势(8); YZPAY-易宝支付(24);CREDIT_CARD_UNIONPAY-银行卡支付(36);DEBIT_CARD_UNIONPAY-银行卡支付(37); ]； PREPAIDCARD-储值卡支付类型，包含如下支付渠道：[PREPAID_CARD-储值卡支付(25);UNIFIED_PREPAID_CARD-储值卡支付(35);OF_PREPAID_CARD-储值卡(106) ]； ECARD-E卡支付类型，包含如下支付渠道：[ECARD-E卡支付(28);OF_E_CARD-有赞E卡(107)]； MARKPAY-标记支付类型，包含如下支付渠道： [ MARK_PAY_WXPAY-标记支付-微信(110); MARK_PAY_ALIPAY-标记支付-支付宝(111); MARK_PAY_POS-标记支付-自有POS刷卡(112); MARK_PAY_DIY-标记收款-自定义(114); MARK_PAY_CREDIT_PAY-标记支付-挂账(205); ] "ENCHASHMENT_GIFT_CARD-礼品卡支付类型，包含如下支付渠道：[ GIFT_CARD-礼品卡支付(33);ENCHASHMENT_GIFT_CARD-礼品卡支付(90); ], DEFAULT-默认值,未支付(0); TENPAY-财付通(5); PEERPAY-找人代付(7); CODPAY-货到付款(9); BAIDUWAP-银行卡支付(12); FX_MERGED-合并付货款(14); UMP_PRESENT-领取赠品(15); UMP_COUPON-优惠兑换(16); FX_SPLITTING-自动付货款(17); AIXUEDAI-爱学贷(18); UMP_REBATE-返利(21); UMP_HB-ump红包(22); PAYZA-(23); PAYPAL-(26); QQPAY-QQ钱包(27); INSTALMENT-分期支付(40); PRIOR_USE-先用后付(49); UN_SETTLED_AMOUNT_PAY-店铺余额支付(80); OF_ONLINE_ACCOUNT-代收账户(100); OF_POS-刷卡(104); OF_TABLE_CARD-二维码台卡(105); ALLIN_SWIPECARD-POS刷卡(113); CHANGE_PAY-有赞零钱(115); UMP_PAY-优惠全额抵扣(116); SUNMI_WX-商米支付(117); SUNMI_ALIPAY-商米支付-支付宝(118); SUNMI_SWIPECARD-商米pos(119); OF_OFFLINE_ACCOUNT-记账账户(200); OF_CASH-现金支付(201); MIXED_PAYMENT-组合支付(202); OUTSIDE_PAYMENT-外部支付(203); TRANSFER_TO_PUBLIC-对公转账(206); OF_ONLINE_PREPAID_ACCOUNT-储值账户(300); OF_ONLINE_DEPOSIT_ACCOUNT-保证金账户(400); ABC_EPAY-农行商E付(4093); ELECTRONIC_BANK_PAY-银联网银支付(4101);
                'pay_type_str' => $row['order_info']['pay_type_str'],//支付类型，同pay_type
                'created' => $row['order_info']['created'],//订单创建时间
                'pay_time' => $row['order_info']['pay_time'],//订单支付时间
                'update_time' => $row['order_info']['update_time'],//订单更新时间
                'consign_time' => $row['order_info']['consign_time'],//订单发货时间（当所有商品发货后才会更新）
                'confirm_time' => $row['order_info']['confirm_time'],//订单确认时间（多人拼团成团）
                'success_time' => $row['order_info']['success_time'],//交易成功时间
                'refund_state' => $row['order_info']['refund_state'],//退款状态 0:未退款; 2:部分退款成功; 12:全额退款成功
                'express_type' => $row['order_info']['express_type'],//物流类型 0:快递发货; 1:到店自提; 2:同城配送; 9:无需发货（虚拟商品订单）
                'shop_name' => $row['order_info']['shop_name'],//店铺名
                //订单基础信息 end
                //订单支付信息 start
                'total_fee' => $row['pay_info']['total_fee'],//优惠前商品总价
                'post_fee' => $row['pay_info']['post_fee'],//邮费
                'payment' => $row['pay_info']['payment'],//最终支付价格 payment=orders.payment的总和
                //订单支付信息 end
                //收货地址信息 start
                'delivery_province' => $row['address_info']['delivery_province'],//省
                'delivery_city' => $row['address_info']['delivery_city'],//市
                'delivery_district' => $row['address_info']['delivery_district'],//区
                'delivery_address' => $row['address_info']['delivery_address'],//详细地址
                'delivery_postal_code' => $row['address_info']['delivery_postal_code'],//邮编
                'receiver_name' => $row['address_info']['receiver_name'],//收货人姓名
                'receiver_tel' => $row['address_info']['receiver_tel'],//收货人手机
                //收货地址信息 end
                //订单标记信息 start
                'buyer_message' => $row['remark_info']['buyer_message'] ?? '',//订单买家留言
                'trade_memo' => $row['remark_info']['trade_memo'] ?? '',//订单商家备注
                //订单标记信息 end
            ];
            $orderDetailResult = Youzan::getOrder($tid);
            $orderDetail = $orderDetailResult['data'] ?? [];
            if ($orderDetail) {
                $orderDetailJson = json_encode($orderDetail);
                $fullInfo = YouZanFullOrderInfo::getByWhere(['tid' => $tid]);
                if (empty($fullInfo)) {
                    YouZanFullOrderInfo::insertData(['tid' => $tid, 'sold_full_order_info' => $soldOrderJson, 'detail_order_info' => $orderDetailJson]);
                } else {
                    YouZanFullOrderInfo::updateData(['sold_full_order_info' => $soldOrderJson, 'detail_order_info' => $orderDetailJson], ['tid' => $tid]);
                }
                $detailDists = [];
                foreach ($orderDetail['delivery_order'] as $deliverRow) {
                    foreach ($deliverRow['dists'] as $dist) {
                        foreach ($dist['dist_items'] as $item) {
                            $detailDists[$item['oid']] = [
                                'oid' => $item['oid'],
                                'dist_id' => $dist['dist_id'],
                                'express_id' => $dist['express_info']['express_id'] ?? 0,
                                'express_no' => $dist['express_info']['express_no'] ?? '',
                                'express_name' => $allExpress[$dist['express_info']['express_id']] ?? '',
                            ];
                        }
                    }
                }
                $detailRefund = [];
                foreach ($orderDetail['refund_order'] as $refundRow) {
                    foreach ($refundRow['oids'] as $item) {
                        $detailRefund[$item['oid']]['refund_id'] = $refundRow['refund_id'];
                        $detailRefund[$item['oid']]['refund_type'] = $refundRow['refund_type'];
                        $detailRefund[$item['oid']]['refund_time'] = $refundRow['refund_time'];
                        $detailRefund[$item['oid']]['refund_state'] = $refundRow['refund_state'];
                    }
                }
                $itemIds = $row['orders'] ? array_column($row['orders'], 'item_id') : [];
                $itemIds = array_unique(array_filter($itemIds));
                $brandUserIds = $itemIds ? YouZanBrandItem::getBrandUserIdByItemIds($itemIds) : [];
                foreach ($row['orders'] as $oRow) {
                    $oid = $oRow['oid'];//订单明细id
                    $isDeliverGoods = $oRow['item_tags']['is_deliver_goods'] ?? false;//是否已发货，电子卡券，虚拟商品无发货标识。
                    if (isset($detailDists[$oid])) {
                        $isDeliverGoods = true;
                    } else {
                        $isDeliverGoods = false;
                    }
                    $ordersDataArr[$tid][$oid] = [
                        //明细基础信息 start
                        'tid' => $tid,//订单号
                        'oid' => $oRow['oid'],//订单明细id
                        'brand_user_id' => $brandUserIds[$oRow['item_id']] ?? 0,//补贴品牌的账户id
                        'alias' => $oRow['alias'],//商品别名
                        'title' => $oRow['title'],//商品名称
                        'item_id' => $oRow['item_id'],//商品id，有赞生成的商品唯一id
                        'item_no' => $oRow['item_no'],//商品编码
                        'item_barcode' => $oRow['item_barcode'],//商品条码
                        'item_type' => $oRow['item_type'],//订单类型，0:普通类型商品; 1:拍卖商品; 5:餐饮商品; 10:分销商品; 20:会员卡商品; 21:礼品卡商品; 23:有赞会议商品; 24:周期购; 30:收银台商品; 31:知识付费商品; 35:酒店商品; 40:普通服务类商品; 71:卡项商品;182:普通虚拟商品; 183:电子卡券商品; 201:外部会员卡商品; 202:外部直接收款商品; 203:外部普通商品; 204:外部服务商品;205:mock不存在商品; 206:小程序二维码;207:积分充值商品;208:付费优惠券商品
                        'sku_id' => $oRow['sku_id'],//规格id（无规格商品为0）
                        'sku_no' => $oRow['sku_no'],//规格编码
                        'sku_barcode' => $oRow['sku_barcode'],//规格条码
                        'sku_properties_name' => $oRow['sku_properties_name'],//规格信息（无规格商品为空）
                        'goods_url' => $oRow['goods_url'],//商品详情链接
                        'pic_path' => $oRow['pic_path'],//商品图片地址
                        'weight' => $oRow['weight'],//商品重量 单位 克
                        'num' => $oRow['num'],//商品数量
                        'price' => $oRow['price'],//单商品原价 单位:元
                        'discount_price' => $oRow['discount_price'],//单商品现价，减去了商品的优惠金额 单位:元
                        'total_fee' => $oRow['total_fee'],//商品优惠后总价 单位:元
                        'payment' => $oRow['payment'],//商品最终均摊价 单位:元
                        'buyer_messages' => $oRow['buyer_messages'],//商品留言
                        //明细基础信息 end
                        //明细发货包裹信息 start
                        'is_deliver_goods' => $isDeliverGoods,//是否已发货，电子卡券，虚拟商品无发货标识。
                        'dist_id' => $detailDists[$oid]['dist_id'] ?? '',//包裹id，由物流生成，用于唯一标识包裹
                        'express_id' => $detailDists[$oid]['express_id'] ?? 0,//物流公司编号
                        'express_name' => $detailDists[$oid]['express_name'] ?? '',//物流公司名称
                        'express_no' => $detailDists[$oid]['express_no'] ?? '',//快递单号
                        //明细发货包裹信息 end
                        //明细商品退款信息 start
                        'refund_id' => $detailRefund[$oid]['refund_id'] ?? '',//有赞生成的退款id
                        'refund_time' => $detailRefund[$oid]['refund_time'] ?? '',//用户申请退款时间，时间格式为yyyy年-MM月-dd日 HH时:mm分:ss秒
                        'refund_type' => $detailRefund[$oid]['refund_type'] ?? '',//退款类型 1:退款-买家申请退款，2:退款-商家主动退款， 3:退款-一键退款，4:换货-零售门店换货，5:网店换货。 以下场景会触发一键退款（一键退款主要是由有赞服务器基于以下条件自动触发）订单关闭退款，拼团未成团退款，返现退款，团购返现退款，小程序拼团退款，送礼子订单未被领取退款，送礼社群版到期自动退款，美业退款，订单少付退款，酒店拒单，拼团扣库存失败，代付过期退款，代付超付退款，外卖拒单退，超付+本金组合退款，上云商家一键退款类型，会员卡发卡失败退款。
                        'refund_state' => $detailRefund[$oid]['refund_state'] ?? 0,//退款状态 1:买家已经申请退款，等待卖家同意， 10:卖家拒绝退款， 20:卖家已经同意退货，等待买家退货， 30:买家已经退货，等待卖家确认收货， 40:卖家未收到货,拒绝退款，45：商家已经发货，等待买家确认收货， 50:退款关闭， 60:退款成功
                        //明细商品退款信息 end
                        //订单信息 start
                        'created' => $orderInfoDataArr[$tid]['created'],//订单创建时间 冗余字段，方便查询
                        'pay_time' => $orderInfoDataArr[$tid]['pay_time'],//订单支付时间 冗余字段，方便查询
                        //订单信息 end
                    ];
                }
            }
        }
        self::logCreateOrderData('开始插入订单数据:' . count($orderInfoDataArr));
        foreach ($orderInfoDataArr as $tid => $insertData) {
            $info = YouZanOrderInfo::getByWhere(['tid' => $tid]);
            $receiverTelUniq = self::getReciverTelUniq($insertData['receiver_tel']);
            if (empty($info)) {
                if ($insertData['receiver_tel']) {
                    $encryptPhoneId = PhoneModel::addExtendPhone($insertData['receiver_tel'], UserExtendPhoneScene::YOUZAN_ORDER_RECEIVER_PHONE);
                    $insertData['receiver_tel_uniq'] = $receiverTelUniq;
                    $insertData['receiver_tel_encrypt_id'] = $encryptPhoneId;
                    $insertData['receiver_tel'] = PhoneCrypto::mask($insertData['receiver_tel']);
                }
                $res = YouZanOrderInfo::insertData($insertData);
            } else {
                if ($insertData['receiver_tel']) {
                    if ($receiverTelUniq != $info['receiver_tel_uniq']) {
                        $encryptPhoneId = PhoneModel::addExtendPhone($insertData['receiver_tel'], UserExtendPhoneScene::YOUZAN_ORDER_RECEIVER_PHONE);
                        $insertData['receiver_tel_uniq'] = $receiverTelUniq;
                        $insertData['receiver_tel_encrypt_id'] = $encryptPhoneId;
                        $insertData['receiver_tel'] = PhoneCrypto::mask($insertData['receiver_tel']);
                    } else {
                        unset($insertData['receiver_tel']);
                    }
                }
                $res = YouZanOrderInfo::updateData($insertData, ['tid' => $tid]);
            }
        }
        self::logCreateOrderData('开始插入订单明细数据:' . count($ordersDataArr));
        foreach ($ordersDataArr as $tid => $ordersRow) {
            foreach ($ordersRow as $oid => $insertData) {
                $info = YouZanOrders::getByWhere(['oid' => $oid]);
                if (empty($info)) {
                    $res = YouZanOrders::insertData($insertData);
                } else {
                    $res = YouZanOrders::updateData($insertData, ['oid' => $oid]);
                }
            }
        }
        return $tids;
    }

    public static function getWaitDeliverCount($brandUserId)
    {
        $where = [
            'brand_user_id' => $brandUserId,
            'is_deliver_goods' => 0,
            'refund_state' => [0, 50]
        ];
        $count = YouZanOrders::selectCountWhere($where);
        return $count;
    }

    public static function exportOrderData($brandUserId, array $params, $exportName, $pageSize = 1000)
    {
        list($data, $total) = self::searchBrandOrder($brandUserId, 1, $pageSize, $params);
        $sheetData = [
            ['cell_title' => '品牌', 'cell_key' => 'A', 'cell_width' => 25, 'value_key' => 'brand'],
            ['cell_title' => '订单编号', 'cell_key' => 'B', 'cell_width' => 30, 'value_key' => 'tid'],
            ['cell_title' => '订单明细id', 'cell_key' => 'C', 'cell_width' => 30, 'value_key' => 'oid'],
            ['cell_title' => '商品发货状态', 'cell_key' => 'D', 'cell_width' => 15, 'value_key' => 'is_deliver_goods'],
            ['cell_title' => '商品退款状态', 'cell_key' => 'E', 'cell_width' => 25, 'value_key' => 'refund_state'],
            ['cell_title' => '商品退款时间', 'cell_key' => 'F', 'cell_width' => 20, 'value_key' => 'refund_time'],
            ['cell_title' => '商品发货物流公司', 'cell_key' => 'G', 'cell_width' => 20, 'value_key' => 'express_name'],
            ['cell_title' => '商品发货物流单号', 'cell_key' => 'H', 'cell_width' => 20, 'value_key' => 'express_no'],
            ['cell_title' => '包裹id', 'cell_key' => 'I', 'cell_width' => 30, 'value_key' => 'dist_id'],
            ['cell_title' => '订单创建时间', 'cell_key' => 'J', 'cell_width' => 25, 'value_key' => 'created'],
            ['cell_title' => '买家付款时间', 'cell_key' => 'K', 'cell_width' => 25, 'value_key' => 'pay_time'],
            ['cell_title' => '商品名称', 'cell_key' => 'L', 'cell_width' => 30, 'value_key' => 'title'],
            ['cell_title' => '商品规格', 'cell_key' => 'M', 'cell_width' => 25, 'value_key' => 'sku_properties_name'],
            ['cell_title' => '商品条码', 'cell_key' => 'N', 'cell_width' => 20, 'value_key' => 'item_barcode'],
            ['cell_title' => '商品数量', 'cell_key' => 'O', 'cell_width' => 15, 'value_key' => 'num'],
            ['cell_title' => '供货价', 'cell_key' => 'P', 'cell_width' => 15, 'value_key' => 'supply_price'],
            ['cell_title' => '供货价小计', 'cell_key' => 'Q', 'cell_width' => 15, 'value_key' => 'total_supply_price'],
            ['cell_title' => '收货人姓名', 'cell_key' => 'R', 'cell_width' => 25, 'value_key' => 'receiver_name'],
            ['cell_title' => '收货人手机号', 'cell_key' => 'S', 'cell_width' => 15, 'value_key' => 'receiver_tel'],
            ['cell_title' => '省', 'cell_key' => 'T', 'cell_width' => 18, 'value_key' => 'delivery_province'],
            ['cell_title' => '市', 'cell_key' => 'U', 'cell_width' => 18, 'value_key' => 'delivery_city'],
            ['cell_title' => '区', 'cell_key' => 'V', 'cell_width' => 18, 'value_key' => 'delivery_district'],
            ['cell_title' => '详细地址', 'cell_key' => 'W', 'cell_width' => 30, 'value_key' => 'delivery_address'],
            ['cell_title' => '买家留言', 'cell_key' => 'X', 'cell_width' => 30, 'value_key' => 'buyer_message'],
            ['cell_title' => '好好住订单备注', 'cell_key' => 'Y', 'cell_width' => 30, 'value_key' => 'trade_memo'],
        ];
        if (is_null($brandUserId)) {
            $sheetData[] = ['cell_title' => '结算价', 'cell_key' => 'Z', 'cell_width' => 15, 'value_key' => 'commission'];
        }
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        foreach ($sheetData as $row) {
            $sheet->setCellValue($row['cell_key'] . '1', $row['cell_title']);
            $sheet->getColumnDimension($row['cell_key'])->setWidth($row['cell_width']);
        }
        $rowNum = 2; // 从第二行开始
        foreach ($data as $info) {
            foreach ($sheetData as $row) {
                $key = $row['value_key'];
                $value = isset($info[$key]) ? $info[$key] : '';
                switch ($key) {
                    case 'is_deliver_goods':
                        $value = ($value == 0) ? '未发货' : '已发货';
                        break;
                    case 'refund_state':
                        $value = $value ? YouZanOrders::REFUND_STATE_MAP[$value] : '';
                        break;
                    case'refund_time':
                        $value = strtotime($value) > 0 ? $value : '';
                        break;
                    case 'pay_time':
                        $value = strtotime($value) > 0 ? $value : '';
                        break;
                    case 'supply_price':
                        $value = $value ?: '';
                        break;
                    case 'total_supply_price':
                        $value = $value ?: '';
                        break;
                }
                $cellKey = $row['cell_key'] . $rowNum;
                $sheet->setCellValue($cellKey, $value);
                $styleArray = [
                    'alignment' => [
                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                    ],
                ];
                $sheet->getStyle($cellKey)->applyFromArray($styleArray);
                if (in_array($row['cell_key'], ['C', 'H'])) {
                    $sheet->getCell($cellKey)->setValueExplicit($value, DataType::TYPE_STRING);
                } else {
                    $sheet->getStyle($cellKey)->getAlignment()->setWrapText(true);
                }
            }
            $rowNum++;
        }
        $exportName = str_replace("+", "%20", urlencode($exportName));
        $fileName = $exportName . date('YmdHis') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    /**
     * 更新订单信息
     * @param array $tids
     * @return void
     */
    public static function updateOrder(array $tids)
    {
        $tids ? self::_async($tids) : [];
    }

    public static function _async_updateOrder(array $tids)
    {
        $tids = array_unique($tids);
        foreach ($tids as $tid) {
            self::searchCreateOrder(null, null, $tid);
        }
    }

    private static function logCreateOrderData($message, array $data = [])
    {
        $msg = date('YmdHis') . '有赞订单｜' . $message;
        if (self::$createDataDebug) {
            $msg .= $data ? ('#' . json_encode($data, JSON_UNESCAPED_UNICODE)) : '';
            var_dump($msg);
        }
        Log::info($msg, $data);
    }

    public static function getReciverTelUniq($receiverTel)
    {
        return $receiverTel ? md5(YouZanOrderInfo::RECEIVER_TEL_SECRETS . $receiverTel) : '';
    }

    public static function batchGetDecryptPhones(array $phoneEncryptIds)
    {
        $result = [];
        $count = count($phoneEncryptIds);
        $pageSize = 300;
        for ($page = 0; ($page * $pageSize) < $count; $page++) {
            $ids = array_slice($phoneEncryptIds, $page * $pageSize, $pageSize);
            if ($ids) {
                $phones = PhoneModel::batchGetExtendPhone($ids, UserExtendPhoneScene::YOUZAN_ORDER_RECEIVER_PHONE);
                $result = $result + $phones;
            }
        }
        return $result;
    }


}